package com.lenovo.lcdm.team.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lenovo.lcdm.common.enums.CommonMsgEnum;
import com.lenovo.lcdm.common.enums.DeleteFlagEnum;
import com.lenovo.lcdm.common.exception.BusinessException;
import com.lenovo.lcdm.common.exception.ServiceException;
import com.lenovo.lcdm.team.common.util.ContextUtil;
import com.lenovo.lcdm.team.common.util.ValidateUtil;
import com.lenovo.lcdm.team.dto.UserAuthDto;
import com.lenovo.lcdm.team.dto.UserDto;
import com.lenovo.lcdm.team.dto.UserPwdDto;
import com.lenovo.lcdm.team.dto.UserQueryDto;
import com.lenovo.lcdm.team.entity.TeamGroup;
import com.lenovo.lcdm.team.entity.TeamRole;
import com.lenovo.lcdm.team.entity.TeamUser;
import com.lenovo.lcdm.team.entity.TeamUserGroup;
import com.lenovo.lcdm.team.enums.LoginTypeEnum;
import com.lenovo.lcdm.team.mapper.TeamUserMapper;
import com.lenovo.lcdm.team.service.*;
import com.lenovo.lcdm.team.vo.GroupVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
* @author sunby1
* @description 针对表【plm_user】的数据库操作Service实现
* @createDate 2023-12-21 17:55:12
*/
@Service
public class TeamUserServiceImpl extends ServiceImpl<TeamUserMapper, TeamUser> implements ITeamUserService {

    private static Logger logger = LoggerFactory.getLogger(TeamUserServiceImpl.class);

    @Autowired
    private ITeamUserGroupService userGroupService;

    @Autowired
    private ITeamGroupService groupService;

    @Autowired
    private ITeamGroupRoleService groupRoleService;

    @Autowired
    private ITeamRoleService roleService;

    @Value("${itsm.bpo}")
    private String businessOwner;

    private static final String LENOVO_EMAIL_SUFFIX = "@lenovo.com";


    @Override
    public List<TeamUser> listByPage(Page page, UserQueryDto userDto) {
        LambdaQueryWrapper<TeamUser> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUser::getDeleted, DeleteFlagEnum.NO.getValue());
        if(userDto != null){
            qw.like(StringUtils.isNotBlank(userDto.getUserName()), TeamUser::getUsername, userDto.getUserName());
            qw.like(StringUtils.isNotBlank(userDto.getItCode()), TeamUser::getItCode, userDto.getItCode());
        }
        qw.orderByAsc(TeamUser::getItCode);
        return this.list(page, qw);
    }

    @Override
    public void saveUser(UserDto userDto) throws BusinessException{
        validateUser(userDto);
        Date now = new Date();
        TeamUser user = null;
        if(userDto.getId() == null){
            user = new TeamUser();
            user.setCreateTime(now);
        }else{
            user = this.getById(userDto.getId());
            if(user == null || user.getDeleted().intValue() == 1){
                throw new BusinessException("User "+ userDto.getItCode() + "does not exist in system!\n" ,CommonMsgEnum.FAIL.getCode());
            }
            if(user.getCreator() != null) {
                userDto.setCreator(user.getCreator());
            }
        }

        BeanUtils.copyProperties(userDto, user);
        //如果有密码，加密
        if(StringUtils.isNotEmpty(userDto.getPassword())){
            user.setPassword(SecureUtil.md5(userDto.getPassword()));
        }else{
            user.setPassword(null);
        }
        //默认远程用户
        if(StringUtils.isEmpty(userDto.getLoginType())){
            user.setLoginType(LoginTypeEnum.REMOTE.getType());
        }
        if(userDto.getEnabled() == null){
            user.setEnabled(1);
        }
        user.setModifyTime(now);
        user.setEmail(user.getItCode() + LENOVO_EMAIL_SUFFIX);
        this.saveOrUpdate(user);
        if(CollectionUtils.isEmpty(userDto.getGroupIds()) && !CollectionUtils.isEmpty(userDto.getGroupNames())){
            LambdaQueryWrapper<TeamGroup> groupQw = new LambdaQueryWrapper<TeamGroup>();
            groupQw.in(TeamGroup::getGroupName, userDto.getGroupNames());
            List<TeamGroup> list = groupService.list(groupQw);
            if(!CollectionUtils.isEmpty(list)) {
                userDto.setGroupIds(list.stream().map(TeamGroup::getId).collect(Collectors.toSet()));
            }
        }
        userGroupService.saveOrUpdateUserGroups(user, userDto.getGroupIds());
    }

    @Override
    public UserDto getUserInfo(Long id) throws Exception{
       TeamUser user = this.getById(id);
       if(user == null || user.getDeleted().intValue() == 1){
           throw new ServiceException("User does not exist in system!\n" ,CommonMsgEnum.FAIL.getCode());
       }
       UserDto userDto = new UserDto();
       BeanUtils.copyProperties(user, userDto);

       List<TeamUserGroup> userGroups = userGroupService.getGroupByUserId(id);
       Set<Long> groupIds = userGroups.stream().map(TeamUserGroup::getGroupId).collect(Collectors.toSet());
       List<TeamGroup> groups = groupService.listByIds(groupIds);
       userDto.setGroups(groups);
       userDto.setGroupIds(groupIds);
       return userDto;
    }

    @Override
    public void deleteUser(String itCode) throws Exception{
        LambdaQueryWrapper<TeamUser> userQw = new LambdaQueryWrapper<>();
        userQw.eq(TeamUser::getItCode, itCode).eq(TeamUser::getDeleted, DeleteFlagEnum.NO.getValue());
        List<TeamUser> users = this.list(userQw);
        if(users.size() == 1){
//            LambdaQueryWrapper<TeamUserGroup> qw = new LambdaQueryWrapper<>();
//            qw.eq(TeamUserGroup::getUserId, users.get(0).getId());
//            userGroupService.remove(qw);
            TeamUser user = users.get(0);
            user.setDeleted(DeleteFlagEnum.YES.getValue());
            user.setModifier(ContextUtil.getCurrentUser());
            user.setModifyTime(new Date());
            this.updateById(user);
        }else if(users.size() > 1){
            throw new ServiceException("ItCode:" + itCode + " exists multiple User!" ,CommonMsgEnum.FAIL.getCode());
        }
    }


    /**
     * 根据itCode查用户
     * @param itCode
     * @return
     */
    public TeamUser getByItCode(String itCode){
        LambdaQueryWrapper<TeamUser> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUser::getItCode, itCode).eq(TeamUser::getDeleted, DeleteFlagEnum.NO.getValue());
        return this.getOne(qw);
    }

    /**
     * 验证用户信息
     *
     * @param userDto
     * @return
     */
    private void validateUser(UserDto userDto) throws BusinessException {
        StringBuffer buffer = new StringBuffer();
        String itCode = userDto.getItCode();
        String email = userDto.getEmail();
        String manager = userDto.getManager();

        // validate itCode
        if (StringUtils.isEmpty(itCode)) {
            buffer.append("ItCode cannot be empty!\n");
        }
        if (StringUtils.isNotEmpty(itCode) && !checkItCode(itCode)) {
            buffer.append("ItCode must be the combination of Latin alphabet, digit or underscore (i.e. _).\n");
        }
        TeamUser temUser = this.getByItCode(itCode);
        if (temUser != null && (userDto.getId() == null || userDto.getId().intValue() != temUser.getId().intValue())) {
            buffer.append("User ").append(itCode).append(" exist in system!\n");
        }

        // validate email
        if (StringUtils.isNotEmpty(email) && !ValidateUtil.checkEmail(email)) {
                buffer.append("Email patten is wrong!");
        }

        // validate manager
        if (StringUtils.isNotEmpty(manager)) {
            LambdaQueryWrapper<TeamUser> managerQw = new LambdaQueryWrapper<>();
            managerQw.eq(TeamUser::getItCode, manager);
            if (this.list(managerQw) == null) {
                buffer.append("Manager does not exist.");
            }
        }

        if (CollectionUtils.isEmpty(userDto.getGroupIds()) && CollectionUtils.isEmpty(userDto.getGroupNames())) {
            buffer.append("user role groups cannot be empty!\n");
        }

        if(buffer.length() > 0){
            throw new BusinessException(buffer.toString(), CommonMsgEnum.FAIL.getCode());
        }
    }

    /**
     * 校验itCode
     * @param itCode
     * @return
     */
    private boolean checkItCode(String itCode) {
        if (itCode == null || itCode.isEmpty()) {
            return false;
        }
        String regex = "([a-z]|[A-Z]|[0-9]|_)*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(itCode);
        return matcher.matches();
    }

    public UserAuthDto getUserAuthorities(String itCode, boolean hasRole){
        LambdaQueryWrapper<TeamUser> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUser::getItCode, itCode);
        qw.eq(TeamUser::getDeleted, DeleteFlagEnum.NO.getValue());
        List<TeamUser> users= this.list(qw);
        if(CollectionUtils.isEmpty(users) || users.size() > 1){
            throw new ServiceException("Cannot find User or find multiple User!" ,CommonMsgEnum.FAIL.getCode());
        }

        Long userId = users.get(0).getId();
        LambdaQueryWrapper<TeamUserGroup> userGroupQw = new LambdaQueryWrapper<>();
        userGroupQw.eq(TeamUserGroup::getUserId, userId);
        List<TeamUserGroup> userGroups = userGroupService.list(userGroupQw);

        List<Long> groupIds = userGroups.stream().map(TeamUserGroup::getGroupId).collect(Collectors.toList());

        UserAuthDto dto = new UserAuthDto();
        if (CollectionUtil.isNotEmpty(groupIds)) {
            List<TeamGroup> groups = groupService.listByIds(groupIds);
            if(hasRole) {
                List<TeamRole> roles = roleService.getByGroupIds(groupIds);
                dto.setRoles(roles);
            }
            dto.setGroups(groups);
        } else {
            if(hasRole) {
                dto.setRoles(Lists.newArrayList());
            }
            dto.setGroups(Lists.newArrayList());
        }
        return dto;
    }

    @Override
    public TeamUser getCurrentUser() {
        LambdaQueryWrapper<TeamUser> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUser::getItCode, ContextUtil.getCurrentUser());
        qw.eq(TeamUser::getDeleted, DeleteFlagEnum.NO.getValue());
        return getOne(qw, false);
    }

    @Override
    public List<GroupVo> getUserGroups(String itcode) {
        UserAuthDto userAuthDto = getUserAuthorities(itcode, false);
        List<GroupVo> groupVos = new ArrayList<>();
        if(userAuthDto != null && CollectionUtil.isNotEmpty(userAuthDto.getGroups())){
            groupVos = userAuthDto.getGroups().stream().map(item->{
                GroupVo groupVo = new GroupVo();
                groupVo.setGroupName(item.getGroupName());
                groupVo.setBusinessOwner(businessOwner);
                groupVo.setGroupDescription(item.getGroupDesc()==null?"":item.getGroupDesc());
                return groupVo;
            }).collect(Collectors.toList());
        }
        return groupVos;
    }

    @Override
    public boolean updateUserName(String itCode, String userName) {
        UpdateWrapper<TeamUser> updateWrapper = Wrappers.update();
        updateWrapper.set("username", userName);
        updateWrapper.eq("it_code", itCode);
        updateWrapper.eq("deleted", DeleteFlagEnum.NO.getValue());
        updateWrapper.eq("login_type", LoginTypeEnum.REMOTE.getType());
        updateWrapper.and(query->query.isNull("username").or().ne("username", userName));
        return update(updateWrapper);
    }

    @Override
    public boolean updateLastLoginTime(String itCode) {
        UpdateWrapper<TeamUser> updateWrapper = Wrappers.update();
        updateWrapper.set("last_login_time", new Date());
        updateWrapper.eq("it_code", itCode);
        updateWrapper.eq("deleted", DeleteFlagEnum.NO.getValue());
        return update(updateWrapper);
    }

    @Override
    public boolean modifyPwd(UserPwdDto userPwdDto, boolean isResetPwd) {
        //check itCode cannot empty
        if(StringUtils.isEmpty(userPwdDto.getItCode())){
            throw new BusinessException("ItCode cannot be empty!", CommonMsgEnum.FAIL.getCode());
        }

        if(!isResetPwd) {
            //check password cannot empty
            if (StringUtils.isEmpty(userPwdDto.getPassword())) {
                throw new BusinessException("Password cannot be empty!", CommonMsgEnum.FAIL.getCode());
            }
        }
        //check newPassword cannot empty
        if(StringUtils.isEmpty(userPwdDto.getNewPassword())){
            throw new BusinessException("New Password cannot be empty!", CommonMsgEnum.FAIL.getCode());
        }

        //query user by itCode
        LambdaQueryWrapper<TeamUser> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUser::getItCode, userPwdDto.getItCode());
        qw.eq(TeamUser::getDeleted, DeleteFlagEnum.NO.getValue());
        TeamUser user = this.getOne(qw);
        if(user == null){
            throw new BusinessException("User does not exist in system!", CommonMsgEnum.FAIL.getCode());
        }

        if(!isResetPwd) {
            //check password
            if (!user.getPassword().equals(SecureUtil.md5(userPwdDto.getPassword()))) {
                throw new BusinessException("Password is wrong!", CommonMsgEnum.FAIL.getCode());
            }
        }

        //update password
        UpdateWrapper<TeamUser> updateWrapper = Wrappers.update();
        updateWrapper.set("password", SecureUtil.md5(userPwdDto.getNewPassword()));
        updateWrapper.set("modify_time", new Date());
        updateWrapper.set("modifier", ContextUtil.getCurrentUser());
        updateWrapper.eq("it_code", userPwdDto.getItCode());
        updateWrapper.eq("deleted", DeleteFlagEnum.NO.getValue());
        return update(updateWrapper);
    }
}




